package com.ihr360.binlog.service;

import com.ihr360.binlog.model.Email;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.MimeMessage;

/**
 * @author
 * @Date
 */
@Service
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private Configuration configuration;
    @Value("${spring.mail.username}")
    private String senter;

    @Override
    public void sendEmailByFreemarker(Email email) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(senter);
        helper.setTo(email.getRecipientMail());
        helper.setSubject(email.getSubject());
        Template template = configuration.getTemplate(email.getTemplate());
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(
                template, email.getContentMap());
        helper.setText(text, true);
        mailSender.send(message);
    }
}
